<template>
  <div class="product-list">
    <div class="filter-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索商品"
        clearable
        style="width: 300px"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <el-select v-model="categoryId" placeholder="选择分类" clearable @change="handleFilter">
        <el-option label="全部分类" :value="null" />
        <el-option
          v-for="category in categories"
          :key="category.id"
          :label="(category.icon || '📦') + ' ' + category.name"
          :value="category.id"
        >
          <span>{{ category.icon || '📦' }} {{ category.name }}</span>
          <span style="color: #8492a6; font-size: 13px; margin-left: 8px;">({{ category.productCount || 0 }})</span>
        </el-option>
      </el-select>
      
      <el-select v-model="sortBy" placeholder="排序方式" @change="handleFilter">
        <el-option label="默认排序" value="default" />
        <el-option label="价格从低到高" value="price_asc" />
        <el-option label="价格从高到低" value="price_desc" />
        <el-option label="销量最高" value="sales" />
      </el-select>
    </div>
    
    <div v-loading="loading" class="product-grid">
      <div
        v-for="product in productList"
        :key="product.id"
        class="product-card"
        @click="goToDetail(product.id)"
      >
        <el-tag v-if="product.stock < 10" type="danger" class="stock-tag">库存紧张</el-tag>
        <div class="product-image">
          <img :src="getImageUrl(product.image)" :alt="product.name" />
        </div>
        <div class="product-info">
          <h4>{{ product.name }}</h4>
          <p class="product-desc">{{ product.description }}</p>
          <div class="product-meta">
            <span class="sales">已售 {{ product.sales || 0 }}</span>
            <span class="stock">库存 {{ product.stock }}</span>
          </div>
          <div class="product-footer">
            <span class="price">¥{{ product.price }}</span>
            <el-button
              type="primary"
              size="small"
              :icon="ShoppingCart"
              :disabled="product.stock === 0"
              @click.stop="addToCart(product)"
            >
              {{ product.stock === 0 ? '已售罄' : '加入购物车' }}
            </el-button>
          </div>
        </div>
      </div>
      
      <el-empty v-if="!loading && productList.length === 0" description="暂无商品" />
    </div>
    
    <el-pagination
      v-if="total > 0"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[12, 24, 36, 48]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleFilter"
      @current-change="handleFilter"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { getProductList, searchProduct } from '@/api/product'
import { getCategoryList } from '@/api/category'
import { ElMessage } from 'element-plus'
import { ShoppingCart } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const cartStore = useCartStore()

const loading = ref(false)
const searchKeyword = ref('')
const categoryId = ref(null)
const sortBy = ref('default')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const productList = ref([])
const categories = ref([])

onMounted(() => {
  loadCategories()
  if (route.query.categoryId) {
    categoryId.value = parseInt(route.query.categoryId)
  }
  loadProducts()
})

watch(() => route.query.categoryId, (val) => {
  if (val) {
    categoryId.value = parseInt(val)
    loadProducts()
  }
})

const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      // 只显示启用状态的分类
      categories.value = res.data.filter(cat => cat.status === 1)
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
    // 使用模拟数据
    categories.value = [
      { id: 1, name: '饮料' },
      { id: 2, name: '零食' },
      { id: 3, name: '日用品' },
      { id: 4, name: '速食' },
      { id: 5, name: '水果' },
      { id: 6, name: '乳制品' }
    ]
  }
}

const loadProducts = async () => {
  loading.value = true
  try {
    // 解析排序参数
    let sortField = null
    let sortOrder = null
    if (sortBy.value === 'price_asc') {
      sortField = 'price'
      sortOrder = 'asc'
    } else if (sortBy.value === 'price_desc') {
      sortField = 'price'
      sortOrder = 'desc'
    } else if (sortBy.value === 'sales') {
      sortField = 'sales'
      sortOrder = 'desc'
    }
    
    // 修正：使用后端接口所需的参数格式
    const requestData = {
      page: currentPage.value,
      pageSize: pageSize.value,
      categoryId: categoryId.value || null,
      name: searchKeyword.value || null,
      sortField: sortField,
      sortOrder: sortOrder,
      status: 1  // 只查询上架商品
    }
    
    const res = await getProductList(requestData)
    if (res.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('加载商品列表失败:', error)
    // 使用模拟数据
    productList.value = Array.from({ length: 12 }, (_, i) => ({
      id: i + 1,
      name: `商品${i + 1}`,
      description: '优质商品，值得信赖',
      price: (Math.random() * 50 + 5).toFixed(2),
      image: 'https://via.placeholder.com/200',
      stock: Math.floor(Math.random() * 100),
      sales: Math.floor(Math.random() * 500)
    }))
    total.value = 100
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadProducts()
}

const handleFilter = () => {
  currentPage.value = 1
  loadProducts()
}

const goToDetail = (id) => {
  router.push(`/customer/products/${id}`)
}

const addToCart = async (product) => {
  if (product.stock === 0) {
    ElMessage.warning('商品已售罄')
    return
  }
  // 传递productId和数量，cartStore.addItem会显示提示信息
  await cartStore.addItem(product.id, 1)
}

// 获取图片URL（处理相对路径和绝对路径）
const getImageUrl = (url) => {
  if (!url) return 'https://via.placeholder.com/200'
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return 'http://localhost:8080' + url
}
</script>

<style lang="scss" scoped>
.product-list {
  .filter-bar {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }
  
  .product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
    min-height: 400px;
    
    .product-card {
      background: white;
      border-radius: 8px;
      overflow: hidden;
      cursor: pointer;
      transition: all 0.3s;
      position: relative;
      
      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        transform: translateY(-5px);
      }
      
      .stock-tag {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 1;
      }
      
      .product-image {
        height: 200px;
        overflow: hidden;
        background: #f5f5f5;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .product-info {
        padding: 15px;
        
        h4 {
          font-size: 16px;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .product-desc {
          font-size: 12px;
          color: #999;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .product-meta {
          display: flex;
          gap: 15px;
          font-size: 12px;
          color: #999;
          margin-bottom: 12px;
        }
        
        .product-footer {
          display: flex;
          align-items: center;
          justify-content: space-between;
          
          .price {
            font-size: 20px;
            color: #ff4d4f;
            font-weight: bold;
          }
        }
      }
    }
  }
  
  .el-pagination {
    display: flex;
    justify-content: center;
    background: white;
    padding: 20px;
    border-radius: 8px;
  }
}
</style>











